{extend name="public/base" /}
{block name="style"}
    <style>

        .copy-btn {
            color: #1AAD19;
            font-size: 14px;
            padding: 0 10px;
            height: 30px;
            line-height: 30px;
            border: 1px solid #1AAD19;
            border-radius: 4px;
            background: transparent;
            cursor: pointer;
            flex-shrink: 0;
            margin-left: 10px;
        }

        /* 上传区域样式（与整体风格统一） */
        .upload-area {
            display: flex;
            align-items: center;
            -webkit-box-flex: 1;
            -webkit-flex: 1;
            flex: 1;
        }
        .weui-uploader__input-box {
            width: 80px;
            height: 80px;
            border: 1px dashed #ddd;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f9f9f9;
        }
        .upload-tip {
            color: #888;
            font-size: 12px;
            margin-top: 8px;
            margin-left: 90px; /* 与上传框对齐 */
        }



        /* 提示信息（统一风格） */
        .tips-box {
            background-color: #f0f7f0;
            border-left: 3px solid #1AAD19;
            padding: 10px 15px;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        .tips-title {
            color: #1AAD19;
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 5px;
            display: flex;
            align-items: center;
        }
        .tips-title i {
            margin-right: 5px;
        }
        .tips-content {
            color: #666;
            font-size: 13px;
            line-height: 1.6;
        }
        .tips-content p {
            margin-bottom: 5px;
        }
        .tips-content p:last-child {
            margin-bottom: 0;
        }
    </style>
{/block}

{block name="content"}
<!-- 头部导航（与所有页面统一） -->
<div class="header">
    <a href="javascript:void(0);" class="back-btn">
        <i class="fa fa-angle-left" style="font-size: 24px;"></i>
    </a>
    <h1 class="header-title">充值</h1>
</div>

<div class='weui-content'>
    <!-- 充值模块（复用统一容器） -->
    <div class="wy-Module">
        <div class="wy-Module-con">
            <!-- 充值提示（优化说明内容） -->
            <div class="tips-box">
                <div class="tips-title">
                    <i class="fa fa-info-circle"></i>充值说明
                </div>
                <div class="tips-content">
                    <p>1. 请确认充币网络与您钱包网络一致，否则可能导致资产丢失</p>
                    <p>2. 提币转账到客服提供的地址后截图上传到该页面</p>
                    <p>3. 不同币种有不同的最低充值限额，请留意输入提示</p>
                </div>
            </div>

            <form class="weui-form" id="rechargeForm">
                <!-- 新增：币种选择 -->
                <div class="weui-form-group">
                    <div class="weui-input-box">
                        <span class="input-label">选择币种</span>
                        <select class="weui-select" id="currency" required>
                            <option value="0">请选择充值币种</option>
                            {foreach name="list" item="vo"}
                            <option value="{$vo.id}">{$vo.coin_name}</option>
                            {/foreach}
                        </select>
                    </div>
                </div>
                <!-- 充币金额（统一输入框样式） -->
                <div class="weui-form-group">
                    <div class="weui-input-box">
                        <span class="input-label">充币金额</span>
                        <i class="fa fa-money input-icon"></i>
                        <input type="number" class="weui-input" id="amount" placeholder="请选择币种后输入" min="0" step="1">
                    </div>
                </div>

                <!-- 充币网络（根据币种动态变化） -->
                <div class="weui-form-group">
                    <div class="weui-input-box">
                        <span class="input-label">充币网络</span>
                        <i class="fa fa-link input-icon"></i>
                        <input type="text" class="weui-input" id="network" placeholder="" min="0" readonly>
                    </div>
                </div>

                <!-- 充值地址（根据币种动态变化，带复制功能） -->
                <div class="weui-form-group">
                    <div class="weui-input-box">
                        <span class="input-label">充值地址</span>
                        <i class="fa fa-qrcode input-icon"></i>
                        <input type="text" class="weui-input" id="address" placeholder="充值地址" readonly>
                        <button type="button" class="copy-btn" id="copyAddress">复制</button>
                    </div>
                </div>

                <!-- 充值截图（上传区域样式统一） -->
                <div class="weui-form-group">
                    <div class="weui-input-box" style="height: auto; padding: 15px; flex-wrap: wrap;">
                        <span class="input-label">转账凭证</span>
                        <div class="upload-area" id="uploadArea">
                            <div class="weui-uploader__input-box">
                                <input id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*">
                            </div>
                        </div>
                    </div>
                    <div class="upload-tip">
                        请上传转账截图（支持JPG、PNG格式，大小不超过5MB）
                    </div>
                </div>
                <!-- 确认按钮（绿色风格统一） -->
                <button type="submit" class="weui-btn weui-btn_primary">确认充值</button>
                <!-- 新增：客服链接 -->
                <div class="customer-service">
                    <a href="{$customer_link}" class="service-link">
                        <i class="fa fa-headphones"></i>充值遇到问题？联系客服
                    </a>
                </div>
            </form>
        </div>
    </div>

    <!-- 底部版权（与所有页面统一） -->
    <div class="copyright">
        © 2025 数字货币交易平台 版权所有
    </div>
</div>

{/block}
{block name="script"}
<script>
    // 币种与地址映射表
    const currencyData = JSON.parse(`{$list|raw|json_encode}`);
    let uploadFile = "";
    $("#currency").change(function (){
        const coin_id = $(this).val();
        $.each(currencyData,function (index,val){
            if (val.id==coin_id) {
                 $("#network").val(val.network);
                 $("#address").val(val.address);
                 return;
            }
        })
    })

    $("#copyAddress").click(function (){
        const address = $("#address").val();
        if (!address) {
            return;
        }
        const textarea = document.createElement('textarea');
        textarea.value = address;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea)
        $.toast('充值地址已经复制', 'success');
    });
    // 3. 图片上传预览与删除逻辑（修复事件绑定问题）
    $(document).on("change", "#uploaderInput", function(e) {
        const file = e.target.files[0];
        if (!file) return;

        // 验证文件类型和大小
        const fileType = file.type.toLowerCase();
        if (!fileType.match(/^image\/(jpg|jpeg|png)$/)) {
            $.toptip('请上传JPG或PNG格式图片', 'error');
            return;
        }
        if (file.size > 5 * 1024 * 1024) { // 5MB
            $.toptip('图片大小不能超过5MB', 'error');
            return;
        }

        // 存储文件（用于后续提交）
        uploadFile = file;

        // 生成预览图
        const reader = new FileReader();
        reader.onload = function(event) {
            const previewHtml = `
                <img class="preview-img" src="${event.target.result}" alt="转账凭证">
                <button type="button" class="copy-btn" id="deleteImg">
                    <i class="fa fa-trash-o"></i> 删除
                </button>
            `;
            $("#uploadArea").html(previewHtml);
        };
        reader.readAsDataURL(file);
    });

    // 图片删除逻辑（事件委托，避免动态元素绑定问题）
    $(document).on("click", "#deleteImg", function() {
        // 恢复上传框
        const uploadHtml = `
            <div class="weui-uploader__input-box">
                <input id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*">
            </div>
        `;
        $("#uploadArea").html(uploadHtml);
        uploadFile = null; // 清空文件缓存
    });
    // 4. 表单提交逻辑（含AJAX上传图片）
    $("#rechargeForm").submit(function(e) {
        e.preventDefault();
        const coinId = $("#currency").val().trim();
        const amount = $("#amount").val().trim();
        if (coinId === "0") {
            $.toptip("请选择充值币种", "error");
            return;
        }
        if (!amount) {
            $.toptip("请输入充币金额", "error");
            return;
        }
        // 获取当前币种的最低金额
        const coinInfo = currencyData.find(item => item.id == coinId);
        const minAmount = parseFloat(coinInfo.pay_min_num);
        const inputAmount = parseFloat(amount);
        if (isNaN(inputAmount) || inputAmount < minAmount) {
            $.toptip(`最低充值金额为${minAmount} ${coinInfo.coin_name.toUpperCase()}`, "error");
            return;
        }
        if (!uploadFile) {
            $.toptip("请上传转账截图", "error");
            return;
        }

        // 4.2 构建FormData（用于上传文件和表单数据）
        const formData = new FormData();
        formData.append("coin_id", coinId);
        formData.append("amount", amount);
        formData.append("pay_img", uploadFile); // 图片文件（后端接收字段名）
        // 4.3 AJAX提交（含文件上传）
        $.showLoading("正在提交充值申请...");
        $.ajax({
            url: "/do-pay.html",
            type: "POST",
            data: formData,
            contentType: false, // 必须为false，避免jQuery处理Content-Type
            processData: false, // 必须为false，避免jQuery序列化FormData
            dataType: "json",
            success: function(res) {
                $.hideLoading();
                if (res.code === 0) {
                    $.toast(res.msg || "充值申请提交成功", function() {
                        location.href = "/pay.html"; // 跳转充值记录页
                    });
                } else {
                    $.toptip(res.msg || "提交失败，请重试", "error");
                }
            },
            error: function(xhr, status, errMsg) {
                $.hideLoading();
                $.toptip("网络异常，请检查网络后重试", "error");
                console.error("上传错误：", errMsg);
            }
        });
    });
</script>
{/block}